package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"social-app/pkg/jwt_token"
)

func Authentication() gin.HandlerFunc {
	return func(c *gin.Context) {

		// 从请求头中获取token
		token := c.GetHeader("Authorization")
		//fmt.Println("Authentication 验证 token: ", token)
		if token == "" {
			panic("请先登录您的账号")
		}

		// 去掉Bearer前缀
		token = token[7:]

		// 验证token
		claims, err := jwt_token.Decode(token)
		if err != nil {
			panic("用户凭证错误")
		}
		fmt.Println("claims user", claims.User)
		c.Set("user_id", claims.User.UserId)
		c.Set("username", claims.User.Username)
		c.Next()
	}
}
